package middle;

import java.util.Arrays;

public class Solution_16 {

    public int threeSumClosest(int[] nums, int target) {
        int min_sub = Integer.MAX_VALUE, a = nums[0], b = nums[1], c = nums[2];
        Arrays.sort(nums);
        // 第一个数字固定为nums[i]
        for (int i = 0; i < nums.length - 2; i++) {
            // 第三个数默认从最右边开始，也就是最大值
            int k = nums.length - 1;
            // 第二个数从i+1开始， 避免出现重复数据
            int j = i + 1;
            while (j < k) {
                int sub = target - nums[i] - nums[j] - nums[k];
                if (Math.abs(sub) < min_sub) {
                    min_sub = Math.abs(sub);
                    a = nums[i];
                    b = nums[j];
                    c = nums[k];
                }
                if (sub > 0) {
                    j++;
                } else if (sub < 0) {
                    k--;
                } else {
                    return target;
                }
            }
        }
        return a + b + c;
    }

    public static void main(String[] args) {
        Solution_16 model = new Solution_16();
        System.out.println(model.threeSumClosest(new int[]{0, 1, 2}, 3));
        System.out.println(model.threeSumClosest(new int[]{-1, 2, 1, -4}, 1));
        System.out.println(model.threeSumClosest(new int[]{0, 0, 0}, 1));
        System.out.println(model.threeSumClosest(new int[]{-4, -9, 0, -7, 5, 3, 8}, -7));
    }
}
